package com.black.knight.chess.utils;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.black.knight.chess.R;
import com.black.knight.chess.SahMatActivity;
import com.black.knight.chess.domain.ChessCommand;
import com.black.knight.chess.domain.DeviceItem;
import com.black.knight.chess.domain.Game;
import com.black.knight.chess.domain.Move;
import com.black.knight.chess.domain.PNGGame.PNGGames;
import com.black.knight.chess.domain.PNGOpening.PNGOpenings;
import com.black.knight.chess.enums.CommandType;
import com.black.knight.chess.enums.NewGame;
import com.black.knight.chess.model.PNGGamesModel;
import com.black.knight.chess.model.SahModel;
import com.black.knight.chess.plugins.BluetoothPlugin;

public class ChessUtil {
	public static void chooseFigure(final SahMatActivity activity, final Move move) {
    	final DeviceItem[] whiteFigures = {
    		    new DeviceItem(activity.getResources().getString(R.string.queen), R.drawable.wq),
    		    new DeviceItem(activity.getResources().getString(R.string.rock), R.drawable.wr),
    		    new DeviceItem(activity.getResources().getString(R.string.knight), R.drawable.wn),
    		    new DeviceItem(activity.getResources().getString(R.string.bishop), R.drawable.wb),
    	};
    	
    	final DeviceItem[] blackFigures = {
    		    new DeviceItem(activity.getResources().getString(R.string.queen), R.drawable.bq),
    		    new DeviceItem(activity.getResources().getString(R.string.rock), R.drawable.br),
    		    new DeviceItem(activity.getResources().getString(R.string.knight), R.drawable.bn),
    		    new DeviceItem(activity.getResources().getString(R.string.bishop), R.drawable.bb),
    	};
    	
    	final DeviceItem[] figures;
    	
    	if(Move.isFigureWhite(move.getFigure())) {
    		figures = whiteFigures;
    	} else {
    		figures = blackFigures;
    	}

		ListAdapter adapter = new ArrayAdapter<DeviceItem>(activity, android.R.layout.select_dialog_item, android.R.id.text1, figures){
	        public View getView(int position, View convertView, ViewGroup parent) {
	            View v = super.getView(position, convertView, parent);
	            TextView tv = (TextView)v.findViewById(android.R.id.text1);

	            tv.setCompoundDrawablesWithIntrinsicBounds(figures[position].icon, 0, 0, 0);

	            int dp5 = (int) (5 * activity.getResources().getDisplayMetrics().density + 0.5f);
	            tv.setCompoundDrawablePadding(dp5);

	            return v;
	        }
		};

    	AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    	builder.setTitle(activity.getResources().getString(R.string.choose_figure));
    	builder.setCancelable(false);
    	builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
    	    public void onClick(DialogInterface dialog, int item) {
    	    	move.setDerivedFigure(figures[item].icon);
    	    	playMove(activity, move);
    	    }
    	});
    	AlertDialog alert = builder.create();
    	alert.show();
    }
	
	public static boolean playMove(SahMatActivity activity, Move move) {
		NewGame gameType = SahModel.getInstance().getGame().getGameType();
		
		if(NewGame.BLUETOOTH.equals(gameType)) {
			if(move.check()) {
				Game game = SahModel.getInstance().getGame();
				
				move.execute(game.getSelectedIndex(), true);
				
				if(move.isSah()) {
					Utils.displayAlertMessage(activity, activity.getResources().getString(R.string.check) + " " + activity.getResources().getString(R.string.invalid_move));
				} else {
					ChessCommand cmd = new ChessCommand();
		    		cmd.setType(CommandType.MOVE);
		    		cmd.setMove(move);
					
		    		BluetoothPlugin.getInstance().sendCommand(cmd);
				}
				
				SahModel.getInstance().play(game.getSelectedIndex(), true);
				game.getMoves().remove(game.getMoves().size() - 1);
				game.togglePlayer();
	    		
	    		return true;
			}
			return false;
    	} else if(NewGame.HUMAN.equals(gameType) && activity.playMove(move) || NewGame.ANALIZE.equals(gameType) && activity.playMove(move)) {
    		activity.setMove(null);
    		return true;
    	} else if(NewGame.COMPUTER.equals(gameType) || NewGame.SOLVE_PROBLEM.equals(gameType)) {
			SahModel.context.clearFilters();
    		
			if(move.check()) {
				if(activity.playMove(move)) {
	    			activity.setMove(null);
	        		return true;
				}
        	} else Utils.displayAlertMessage(activity, activity.getResources().getString(R.string.invalid_move));
			
			return false;
    	}
		
		return false;
	}
	
	public static int getChessATOI(char alfa) {
		return alfa - 'a';
	}
	
	public static String getColumnFlag(int column) {
		return String.valueOf((char)('a' + column));
	}
	
	public static String getChessCoords(int hPos, int vPos) {
		return (char)('a' + hPos) + "" + (8 - vPos);
	}
	
	public static String getFigureFlag(int figure) {
		if(figure == R.drawable.bb || figure == R.drawable.wb) return "B";
		else if(figure == R.drawable.bq || figure == R.drawable.wq) return "Q";
		else if(figure == R.drawable.bk || figure == R.drawable.wk) return "K";
		else if(figure == R.drawable.bn || figure == R.drawable.wn) return "N";
		else if(figure == R.drawable.br || figure == R.drawable.wr) return "R";
		
		return "";
	}
	
	public static String getFigureFANFlag(int figure) {
		if(figure == R.drawable.bb) return "b";
		else if(figure == R.drawable.bq) return "q";
		else if(figure == R.drawable.bk) return "k";
		else if(figure == R.drawable.bn) return "n";
		else if(figure == R.drawable.br) return "r";
		else if(figure == R.drawable.bp) return "p";
		else if(figure == R.drawable.wb) return "B";
		else if(figure == R.drawable.wq) return "Q";
		else if(figure == R.drawable.wk) return "K";
		else if(figure == R.drawable.wn) return "N";
		else if(figure == R.drawable.wr) return "R";
		else if(figure == R.drawable.wp) return "P";		
		return "";
	}
	
	public static Integer getFigure(char fenFlag) {
		if('b' == fenFlag) return R.drawable.bb;
		else if('q' == fenFlag) return R.drawable.bq;
		else if('k' == fenFlag) return R.drawable.bk;
		else if('n' == fenFlag) return R.drawable.bn;
		else if('r' == fenFlag) return R.drawable.br;
		else if('p' == fenFlag) return R.drawable.bp;
		else if('B' == fenFlag) return R.drawable.wb;
		else if('Q' == fenFlag) return R.drawable.wq;
		else if('K' == fenFlag) return R.drawable.wk;
		else if('N' == fenFlag) return R.drawable.wn;
		else if('R' == fenFlag) return R.drawable.wr;
		else if('P' == fenFlag) return R.drawable.wp;
		
		return R.drawable.empty;
	}
	
	public static void displayCurrentOpening() {
		try {
			if(SahModel.getInstance().getFenString() != null) return;
			
			Cursor cursor = PNGGamesModel.getOpeningsWhere(PNGGames.PNG + " = '" + SahModel.getInstance().getGame().toPGNGame() + "'");
			if(!cursor.moveToFirst()) {
				cursor = PNGGamesModel.getOpeningsWhere(PNGGames.PNG + " like '%" + SahModel.getInstance().getGame().toPGNGame() + "%'");
			}
			
			if(cursor.moveToFirst()) {
				String desc = cursor.getString(cursor.getColumnIndex(PNGOpenings.DESCRIPTION));
				cursor.close();
				Utils.displayToastMessage(SahModel.context, desc);
			}
		} catch (SQLiteException e) { }
	}
	
    public static String getCategoryName(int i) {
    	if(i == 0) return "problems";
    	else if(i == 1) return "my_games";
    	else if(i == 2) return "games_collection";
    	else if(i == 3) return "openings";
    	else return "";
    }
}
